﻿/*
--------------------------------------
File: MyImage.cs
Project: Themaopdracht 7
Author: Maarten Kroon

Description:
Converts a bitmap image to an int array and vise versa
--------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace THO7_Team8
{
    internal static class MyImage
    {
        //Converts a bitmap image to an array
        public static int[] BmpToArray(Bitmap bitmap)
        {
            Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData bitmapData =
                bitmap.LockBits(rectangle, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                bitmap.PixelFormat);
            IntPtr ptr = bitmapData.Scan0;
            int size = (bitmapData.Stride / 4) * bitmap.Height;

            int[] returnArray = new int[size];
            Marshal.Copy(ptr, returnArray, 0, size);
            bitmap.UnlockBits(bitmapData);
            return returnArray;
        }

        //Converts an array to a bitmap image
        public static Bitmap ArrayToBmp(int[] array, Bitmap originalBitmap)
        {
            Rectangle rectangle = new Rectangle(0, 0, originalBitmap.Width, originalBitmap.Height);

            Bitmap newBmp = new Bitmap(originalBitmap);
            BitmapData bitmapData =
                newBmp.LockBits(rectangle, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                newBmp.PixelFormat);
            IntPtr ptr = bitmapData.Scan0;
            int size = (bitmapData.Stride / 4) * newBmp.Height;

            Marshal.Copy(array, 0, ptr, size);
            newBmp.UnlockBits(bitmapData);
            return newBmp;
        }

        public static Bitmap makeMonochrome(Bitmap originalBitmap)
        {
            int[] originalArray = BmpToArray(originalBitmap);
            int[] modifiedArray = new int[originalArray.Length];

            for (int i = 0; i < originalArray.Length; i++)
            {
                if (originalArray[i] > -8388608)
                {
                    modifiedArray[i] = -1;
                }
                else
                {
                    modifiedArray[i] = -16777216;
                }
            }
            Bitmap modifiedBitmap = new Bitmap(originalBitmap);
            modifiedBitmap = ArrayToBmp(modifiedArray, originalBitmap);
            return modifiedBitmap;
        }
    }
}